package com.hong;

import java.util.concurrent.Exchanger;

public class ExchangerDemo {

    public static void main(String[] args) {
        // 创建一个Exchanger对象，用于交换数据
        Exchanger<String> exchanger = new Exchanger<>();

        // 创建并启动第一个线程，它将携带数据"Data from Thread 1"进行交换
        Thread producer = new Thread(() -> {
            try {
                String producedData = "Data from Thread 1";
                String consumerData = exchanger.exchange(producedData);
                System.out.println("Thread 1 received: " + consumerData);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.err.println("Thread 1 was interrupted");
            }
        });

        // 创建并启动第二个线程，它将携带数据"Data from Thread 2"进行交换
        Thread consumer = new Thread(() -> {
            try {
                String producedData = "Data from Thread 2";
                // 为了让示例更清晰，让第二个线程稍微延迟一会儿，确保第一个线程先到达交换点
                Thread.sleep(100);
                String producerData = exchanger.exchange(producedData);
                System.out.println("Thread 2 received: " + producerData);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.err.println("Thread 2 was interrupted");
            }
        });

        // 创建并启动第二个线程，它将携带数据"Data from Thread 2"进行交换
        Thread consumer1 = new Thread(() -> {
            try {
                String producedData = "Data from Thread 3";
                // 为了让示例更清晰，让第二个线程稍微延迟一会儿，确保第一个线程先到达交换点
                Thread.sleep(100);
                String producerData = exchanger.exchange(producedData);
                System.out.println("Thread 3 received: " + producerData);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.err.println("Thread 3 was interrupted");
            }
        });

        // 启动线程
        producer.start();
        consumer.start();
        consumer1.start();
    }
}
